package com.yonyou.ucf.mdf.app.controller.isv;

import com.alibaba.fastjson.JSON;
import com.yonyou.ucf.mdd.ext.core.AppContext;
import com.yonyou.ucf.mdf.app.common.ResultMessage;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.isv.router.module.InnerRequestParamBO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ClassUtils;
import org.apache.http.Consts;
import org.apache.http.entity.ContentType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping(SyncCharacterInnerController.PATH_INNER_PREFIX)
public class SyncCharacterInnerController {

  public static final String PATH_INNER_PREFIX = "/rest/v1/abpaas/isv/inner";

  @RequestMapping(value = "/synccharacter", method = RequestMethod.POST)
  public void handleInnerBillCodeRequest(
          @RequestBody InnerRequestParamBO innerRequestParamBO,
          HttpServletRequest request,
          HttpServletResponse httpResponse)
          throws Exception {
    Map<String, String> iuapContext = innerRequestParamBO.getIuapContext();
    String className = innerRequestParamBO.getClassName();
    String methodName = innerRequestParamBO.getMethodName();
    List<String> params = innerRequestParamBO.getParams();
    List<String> paramTypes = innerRequestParamBO.getParamTypes();
    if (iuapContext != null) {
      // buildBillCodeContext(iuapContext);
    }

    int size = params.size();
    Class<?>[] classes = new Class[size];
    Object[] objects = new Object[size];
    for (int i = 0; i < size; i++) {
      String paramType = paramTypes.get(i);
      Class<?> clazz = ClassUtils.getClass(paramType, false);
      classes[i] = clazz;
      objects[i] = JSON.parseObject(params.get(i), clazz);
    }
    String[] classNameSplit = className.split("\\.");
    int length = classNameSplit.length;

    Object objectClass = AppContext.getBean(classNameSplit[length - 1]);
    if (objectClass == null) {
      String errorMessage = className + " not a specified interface";
      log.error(errorMessage);
      throw new Exception(errorMessage);
    }
    Method method = objectClass.getClass().getMethod(methodName, classes);
    Object resultObject = method.invoke(objectClass, objects);
    httpResponse.setHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
    renderJson(httpResponse, ResultMessage.data(resultObject));
  }

  /** 根据请求体中的用户信息设置上下文用户信息 */
  /*private void buildBillCodeContext(Map<String, String> iuapContext) {
    String tenantId = iuapContext.get(TENANT_ID);
    String userId = iuapContext.get(USER_ID);
    TokenResult tempToken = authApi.generateToken(tenantId, userId);
    if (tempToken != null) {
      String yhtAccessToken = tempToken.getToken();
      CommonAuthResult commonAuthResult = new CommonAuthResult(tenantId, userId);
      ISVBuildContextUtil.buildContext(commonAuthResult, yhtAccessToken, "");
    }
  }*/

  private void renderJson(HttpServletResponse response, String json) {
    response.setCharacterEncoding(Consts.UTF_8.name());
    response.setContentType(ContentType.APPLICATION_JSON.getMimeType());
    try {
      response.setHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
      response.getWriter().write(json);
    } catch (IOException e) {
      log.error("exception when render json", e);
    }
  }
}
